import sys
import os
import logging
import json
from typing import Dict, List, Any, Optional

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_客户所在省份(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None
) -> Dict[str, Any]:
    """
    客户所在省份 - 指标计算函数
    
    ## 指标说明
    该指标用于获取客户所在省份信息，直接从客户表中查询省份字段，无需复杂计算。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 5895,
        "questionnaire_ids": [11158, 11159]
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok",
        "code": 0,
        "result": [
            {
                "calcVals": [
                    {
                        "val": [
                            {
                                "key": "default",
                                "val": "四川省"
                            }
                        ]
                    }
                ]
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 客户所在省份, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()

        # 1. 查询项目对应的客户编码
        client_sql = """
        SELECT client_code 
        FROM dp_njc.client_item 
        WHERE id = %s
        """
        client_info = db.fetchone(client_sql, (project_id,))
        if not client_info:
            raise ValueError(f"未找到项目ID={project_id}的客户信息")

        client_code = client_info['client_code']
        logger.info(f"查询到客户编码: {client_code}")

        # 2. 查询客户省份
        province_sql = """
        SELECT province 
        FROM dp_njc.client_info 
        WHERE client_code = %s
        """
        province_info = db.fetchone(province_sql, (client_code,))
        if not province_info:
            raise ValueError(f"未找到客户编码={client_code}的省份信息")

        province = province_info['province']
        logger.info(f"查询到客户所在省份: {province}")

        # 3. 构建返回结果
        result_data = [{
            "key": "default",
            "val": province
        }]

        logger.info(f"指标 '客户所在省份' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": [{
                "calcVals": [{
                    "val": result_data
                }]
            }]
        }

    except Exception as e:
        logger.error(f"计算指标 '客户所在省份' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 客户所在省份",
            "code": 500,
            "error": str(e)
        }